package com.familytree.service.impl;

import com.familytree.model.User;
import com.familytree.repository.UserRepository;
import com.familytree.service.UserService;
import com.familytree.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public User createUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreateDate(LocalDate.now());
        user.setUpdateDate(LocalDate.now());
        userRepository.insert(user);
        return user;
    }

    @Override
    public String login(String username, String password) {
        User user = findByUsername(username);
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        return jwtUtil.generateToken(username);
    }

    @Override
    public void logout(String token) {
        // JWT是无状态的，服务端不需要处理登出逻辑
        // 如果需要实现登出，可以在这里添加token黑名单等机制
    }
} 